<?php
  /*
 	 * 无想一刀:atongmz@foxmail.com
 	 * gitee: https://gitee.com/Jane_kang
 	 *以下api通过互联网收集整理以及本人补充
 	 *收集不易请各位小哥哥点个小红心
 	 *问题反馈以及建议请联系我的邮箱
     */

class Alibaba {
	private $AccessKeyId;
	private $AccessKeySecret;
	private $Endpoint = 'alidns.aliyuncs.com'; //API接入域名
	private $Version = '2015-01-09'; //API版本号

	function __construct($AccessKeyId, $AccessKeySecret){
		$this->AccessKeyId = $AccessKeyId;
		$this->AccessKeySecret = $AccessKeySecret;
	}

	//查询余额
	public function QueryAccountBalance(){
	    $data['Endpoint']='business.aliyuncs.com';
	    $data['Version']='2017-12-14';
		$param = ['Action' => __FUNCTION__];
		return $this->request($param,$data, true);
	
	}
	public function GetAccountAlias(){
	    $data['Endpoint']='ram.aliyuncs.com';
	    $data['Version']='2015-05-01';
		$param = ['Action' => __FUNCTION__];
		return $this->request($param,$data, true);
	
	}
	//获取域名解析记录列表
	public function DescribeDomainRecords($DomainName,$RRKeyWord){
		$param = ['Action' => __FUNCTION__, 'DomainName' => $DomainName, 'RRKeyWord' => $RRKeyWord];
	    $vcc=$this->request($param,' ', true);
        return $vcc["DomainRecords"]["Record"][0]["Value"];
	}
	

	//获取域名列表
	public function DescribeDomains($PageSize=100){
		$param = ['Action' => __FUNCTION__, 'PageSize' => $PageSize];
	    return $this->request($param,' ', true);
	}
	
	
  //获取子域名解析记录列表
	public function DescribeSubDomainRecords($SubDomain){
		$param = ['Action' => __FUNCTION__, 'SubDomain' => $SubDomain];
		return $this->request($param,' ', true);
	}

	//添加解析记录
	public function AddDomainRecord($DomainName, $RR, $Type, $Value, $Line = 'default', $TTL = 600){
		$param = ['Action' => __FUNCTION__, 'DomainName' => $DomainName, 'RR' => $RR, 'Type' => $Type, 'Value' => $Value, 'Line' => $Line, 'TTL' => $TTL];
		return $this->request($param,' ');
	}

	//修改解析记录
	public function UpdateDomainRecord($RecordId, $RR, $Type, $Value, $Line = 'default', $TTL = 600){
		$param = ['Action' => __FUNCTION__, 'RecordId' => $RecordId, 'RR' => $RR, 'Type' => $Type, 'Value' => $Value, 'Line' => $Line, 'TTL' => $TTL];
		return $this->request($param,' ');
	}

	//删除解析记录
	public function DeleteDomainRecord($RecordId){
		$param = ['Action' => __FUNCTION__, 'RecordId' => $RecordId];
		return $this->request($param,' ');
	}

	//设置解析记录状态
	public function SetDomainRecordStatus($RecordId, $Status){
		$param = ['Action' => __FUNCTION__, 'RecordId' => $RecordId, 'Status' => $Status];
		return $this->request($param,' ');
	}


	//签名方法
	private function aliyunSignature($parameters, $accessKeySecret, $method)
	{
		ksort($parameters);
		$canonicalizedQueryString = '';
		foreach ($parameters as $key => $value) {
			$canonicalizedQueryString .= '&' . $this->percentEncode($key). '=' . $this->percentEncode($value);
		}
		$stringToSign = $method . '&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
		$signature = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret."&", true));

		return $signature;
	}
	private function percentEncode($str)
	{
		$res = urlencode($str);
		$res = preg_replace('/\+/', '%20', $res);
		$res = preg_replace('/\*/', '%2A', $res);
		$res = preg_replace('/%7E/', '~', $res);
		return $res;
	}
	//请求方法（当需要返回列表等数据时，returnData=true）
	private function request($param,$data, $returnData=false){
	    $Endpoint=$data['Endpoint'];
	    if ($data['Endpoint']=null) {
	    $Endpoint=$this->Endpoint;
	    }
	    $Version=$data['Version'];
	    if ($data['Version']=null) {
	    $Version=$this->Version;
	    }
		if(empty($this->AccessKeyId)||empty($this->AccessKeySecret))return false;
		$url='https://'.$Endpoint.'/';
		$data=array(
			'Format' => 'JSON',
			'Version' => $Version,
			'AccessKeyId' => $this->AccessKeyId,
			'SignatureMethod' => 'HMAC-SHA1',
			'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
			'SignatureVersion' => '1.0',
			'SignatureNonce' => $this->random(8));
		$data=array_merge($data, $param);
		$data['Signature'] = $this->aliyunSignature($data, $this->AccessKeySecret, 'POST');
		$ch=curl_init($url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		$json=curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		$arr=json_decode($json,true);
		if($returnData==true){
			return $arr;
		}else{
			if($httpCode==200){
				return true;
			}else{
				return $arr['Message'];
			}
		}
	}
	private function random($length, $numeric = 0) {
		$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
		$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
		$hash = '';
		$max = strlen($seed) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $seed[mt_rand(0, $max)];
		}
		return $hash;
	}
}
